package com.hanter.android.radui.mvp;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.lang.ref.WeakReference;

/**
 * 实现BasePresenter的基类
 */
public class BasePresenterImpl<T extends BaseView> implements BasePresenter<T> {

    private static final String TAG = "BasePresenterImpl";

    private WeakReference<T> weakReference;

    @Override
    public void attachView(@NonNull T view) {
        weakReference = new WeakReference<>(view);
        view.getLifecycle().addObserver(this);
    }

    @Override
    public void detachView() {
        if (weakReference != null) {
            weakReference.get().getLifecycle().removeObserver(this);
            weakReference.clear();
            weakReference = null;
        }
    }

    @Nullable
    @Override
    public T getView() {
        if (weakReference != null) {
            return weakReference.get();
        } else {
            return null;
        }
    }

    @Override
    public boolean isViewAttached() {
        return weakReference != null && weakReference.get() != null;
    }

    @Override
    public boolean isViewDetached() {
        return weakReference == null || weakReference.get() == null;
    }
}
